//
//  CarsTableViewCell.m
//  Honda
//
//  Created by Xiaolong Zhang on 13-4-24.
//  Copyright (c) 2013年 HeninHoo. All rights reserved.
//

#import "CarsTableViewCell.h"
#import "CarInfo.h"
#import "NetworkManager.h"

@interface CarsTableViewCell ()
@end

@implementation CarsTableViewCell
@synthesize carNameLab      =   _carNameLab;
@synthesize stateLab        =   _stateLab;
@synthesize stateBtn        =   _stateBtn;
@synthesize progressView    =   _progressView;
@synthesize line            =   _line;
@synthesize carInfo         =   _carInfo;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.carNameLab.frame = CGRectMake(5, 23, 64, 20);
        self.stateLab.frame = CGRectMake(79, 25, 180, 15);
        self.progressView.frame = CGRectMake(79, 27.5, 180, 11);
        self.stateBtn.frame = CGRectMake(274, 20, 20, 27);
        self.line.frame = CGRectMake(0, 63, CGRectGetWidth(self.frame), 2);
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDownloadStateChange:) name:Download_State_Change object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decompressComplete:) name:Decompress_Complete object:nil];
    }
    
    return self;
}

- (UILabel*)carNameLab {
    if (nil == _carNameLab) {
        _carNameLab = [[UILabel alloc] init];
        _carNameLab.backgroundColor = [UIColor clearColor];
        _carNameLab.textAlignment = NSTextAlignmentRight;
        _carNameLab.font = [UIFont systemFontOfSize:16];
        _carNameLab.textColor = [UIColor colorWithRed:66 / 255.0 green:66 / 255.0 blue:66 / 255.0 alpha:1.0];
        [self addSubview:_carNameLab];
    }
    
    return _carNameLab;
}

- (UILabel*)stateLab {
    if (nil == _stateLab) {
        _stateLab = [[UILabel alloc] init];
        _stateLab.backgroundColor = [UIColor clearColor];
        _stateLab.textAlignment = NSTextAlignmentLeft;
        _stateLab.font = [UIFont systemFontOfSize:12];
        _stateLab.textColor = [UIColor colorWithRed:99 / 255.0 green:99 / 255.0 blue:99 / 255.0 alpha:1.0];
        
        [self addSubview:_stateLab];
    }
    
    return _stateLab;
}

- (UIButton*)stateBtn {
    if (nil == _stateBtn) {
        _stateBtn = [[UIButton alloc] init];
        _stateBtn.backgroundColor = [UIColor clearColor];
        [_stateBtn setBackgroundImage:[UIImage imageNamed:@"main_resume_button"] forState:UIControlStateNormal];
        [_stateBtn addTarget:self action:@selector(onTapStateButton:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:_stateBtn];
    }
    
    return _stateBtn;
}

- (UIProgressView*)progressView {
    if (nil == _progressView) {
        _progressView = [[UIProgressView alloc] init];
        [_progressView setProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.progressImage = [[UIImage imageNamed:@"main_download_progress"] resizableImageWithCapInsets:UIEdgeInsetsMake(1.5, 5, 1.5, 7)];
        _progressView.trackImage = [[UIImage imageNamed:@"main_download_progress_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(1.5, 5, 1.5, 7)];
        
        [self addSubview:_progressView];
    }
    
    return _progressView;
}

- (UIImageView*)line {
    if (nil == _line) {
        _line = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"main_download_line"]];
        
        [self addSubview:_line];
    }
    
    return _line;
}

- (void) setCarInfo:(CarInfo *)carInfo {
    _carInfo = carInfo;
       NSString* carName = _carInfo.name;
    
//    if ([carName isEqualToString:@"company.zip"]) {
//        carName=@"广本品牌";
//    }
    
   
    [self.carNameLab setText:NSLocalizedStringFromTable(carName, @"InfoPlist", nil)];
    self.carNameLab.font = [UIFont systemFontOfSize:11];
//    if (![carName hasSuffix:@".zip"]) {
//        
//        //self.carNameLab.text = [[carName componentsSeparatedByString:@"."] objectAtIndex:0];
//        //self.carNameLab.font = [UIFont systemFontOfSize:12];
//    }
    if ([NSString invalidString:_carInfo.urlStr]) {
        [self carInfoIsTheLatestVersion];
    } else if (Default_State == _carInfo.downloadCarObj.state) {
        [self carInfoSholdUpdate];
    }
    
    if (!self.progressView.hidden) {
        [self updateProgress];
    }

    [self stateChangeShow];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    SafeRelease(_progressView);
    SafeRelease(_stateBtn);
    SafeRelease(_stateLab);
    SafeRelease(_carNameLab);
    [super dealloc];
}

#pragma mark - 
- (void)onTapStateButton:(UIButton*)stateButton {
    self.progressView.hidden = NO;
    self.stateLab.hidden = YES;
    
    switch (self.carInfo.downloadCarObj.state) {
        case DecompressionError_State:
        {
            NSError * error = nil;
            self.carInfo.downloadCarObj.progress = 0;
            [[NSFileManager defaultManager] removeItemAtPath:self.carInfo.downloadCarObj.tempFilePath error:&error];
            [[NSFileManager defaultManager] removeItemAtPath:self.carInfo.downloadCarObj.tempInfoPath error:&error];
            if (nil != error) {
                NSLog(@"error:%@", error);
            }
            [[NetworkManager getInstance] cancelTaskByIndentifier:self.carInfo.name];
        }
        case DownloadError_State:
        case Default_State:
        case Pausing_State:
        {
            self.carInfo.downloadCarObj.state = Downloading_State;
            [self stateChangeShow];
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationStartDownloadCarTask object:self.carInfo];
        }
            break;
        case Downloading_State:
        {
            self.carInfo.downloadCarObj.state = Pausing_State;
            [NSKeyedArchiver archiveRootObject:self.carInfo.downloadCarObj toFile:self.carInfo.downloadCarObj.tempInfoPath];
            [self stateChangeShow];
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationCancelDownloadCarTask object:self.carInfo];
            
        }
            break;
        case Waitting_State:
            break;
        case Finish_State:
            break;
        case Decompressioning_State:
            break;
        default:
            break;
    }
}

- (void)carInfoIsTheLatestVersion {
    self.stateLab.hidden = NO;
    self.stateLab.text = @"已经是最新版本！";
    self.stateBtn.hidden = YES;
    self.progressView.hidden = YES;
}

- (void)carInfoSholdUpdate {
    self.stateLab.hidden = NO;
    self.stateLab.text = @"是否下载最新版本？";
    self.stateBtn.hidden = NO;
    self.progressView.hidden = YES;
}

-(void)onUpdateProgress:(NSNotification *)notify
{
    NetworkTask* task = notify.object;
    
    if([task.carInfo.downloadCarObj.uuid isEqualToString:self.carInfo.downloadCarObj.uuid])
    {
        self.carInfo = task.carInfo;
        [self performSelectorOnMainThread:@selector(updateProgress) withObject:nil waitUntilDone:NO];
    }
}

- (void)updateProgress {
    [self.progressView setProgress:self.carInfo.downloadCarObj.progress];
}

- (void)onSuccessDownloadCars:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnProgress object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    self.carInfo.downloadCarObj.state = Finish_State;
    [self stateChangeShow];
}

- (void)onFailDownloadCars:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnProgress object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    self.carInfo.downloadCarObj.state = DownloadError_State;
    [self stateChangeShow];
}

//- (void)decompressionCarZipFile {
//    if (![[NSFileManager defaultManager] fileExistsAtPath:self.carInfo.downloadCarObj.saveFilePath]) {
//        self.carInfo.downloadCarObj.state = DecompressionError_State;
//    } else {
//        NSString* car = [[self.carInfo.name componentsSeparatedByString:@"."] objectAtIndex:0];
//        NSString* path = [NSString stringWithFormat:@"%@/%@", self.carInfo.downloadCarObj.saveAutosPath, car];
//        if ([car isEqualToString:@"company"]) {
//            path = self.carInfo.downloadCarObj.saveAutosPath;
//        }
//        BOOL isDir;
//        if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir] && isDir) {
//            NSError* error = nil;
//            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
//            if (nil != error) {
//                NSLog(@"error:%@", error);
//            }
//        }
//        
//        [[ZipArchiveManager SharedInstance] decompressionWithCarInfo:self.carInfo];
//        self.carInfo.downloadCarObj.state = Decompressioning_State;
//    }
//    
//    [self stateChangeShow];
//}

-(void)decompressComplete:(NSNotification *)notify {
    CarInfo* carInfo = notify.object;
    if ([self.carInfo.downloadCarObj.uuid isEqualToString:carInfo.downloadCarObj.uuid]) {
        
        self.carInfo.urlStr = nil;
        self.carInfo.downloadCarObj.state = carInfo.downloadCarObj.state;
        [self stateChangeShow];
        
        [[ConfigCodeHelper shareInstance] updateSourceCarsFileByKey:self.carInfo.name];
        
    }
}

-(void)onDownloadStateChange:(NSNotification *)notify
{
    CarInfo* carInfo = notify.object;
    if ([carInfo.downloadCarObj.uuid isEqualToString:self.carInfo.downloadCarObj.uuid]) {
        [self performSelectorOnMainThread:@selector(stateChangeShow) withObject:nil waitUntilDone:NO];
    }
}

-(void)stateChangeShow
{
    switch (self.carInfo.downloadCarObj.state) {
        case Default_State:
            [self.stateBtn setBackgroundImage:[UIImage imageNamed:@"main_resume_button"] forState:UIControlStateNormal];
            self.stateLab.hidden = NO;
            self.progressView.hidden = YES;
            break;
        case Pausing_State:
            [self.stateBtn setBackgroundImage:[UIImage imageNamed:@"main_resume_button"] forState:UIControlStateNormal];
            self.stateLab.hidden = YES;
            self.progressView.hidden = NO;
            break;
        case Downloading_State:
            [self.stateBtn setBackgroundImage:[UIImage imageNamed:@"main_pause_button"] forState:UIControlStateNormal];
            self.stateLab.hidden = YES;
            self.progressView.hidden = NO;
            break;
        case Waitting_State:
            [self.stateBtn setBackgroundImage:[UIImage imageNamed:@"main_pause_button"] forState:UIControlStateNormal];
            self.stateLab.hidden = YES;
            self.progressView.hidden = NO;
            break;
        case Finish_State:
            if (IsVideo == self.carInfo.downloadCarObj.objType) {
                self.carInfo.downloadCarObj.state = DecompressionFinish_State;
                [[NSNotificationCenter defaultCenter] postNotificationName:Decompress_Complete object:self.carInfo];
            } else {
//                [self decompressionCarZipFile];
                self.stateBtn.hidden = YES;
                self.stateLab.hidden = NO;
                self.stateLab.text = @"开始解压";
                self.progressView.hidden = YES;
            }
            break;
        case DownloadError_State:
            if (IsVideo == self.carInfo.downloadCarObj.objType) {
                [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", self.carInfo.downloadCarObj.saveAutosPath, self.carInfo.name] error:nil];
            }
            
            [self.stateBtn setBackgroundImage:[UIImage imageNamed:@"main_resume_button"] forState:UIControlStateNormal];
            self.stateBtn.hidden = NO;
            self.stateLab.hidden = NO;
            self.progressView.hidden = YES;
            self.stateLab.text = @"下载失败！";
            break;
        case DecompressionError_State:
            [self.stateBtn setBackgroundImage:[UIImage imageNamed:@"main_resume_button"] forState:UIControlStateNormal];
            self.stateBtn.hidden = NO;
            self.stateLab.hidden = NO;
            self.progressView.hidden = YES;
            self.stateLab.text = @"文件损坏，请重新下载！";
            break;
        case Decompressioning_State:
            self.stateBtn.hidden = YES;
            self.stateLab.hidden = NO;
            self.stateLab.text = @"解压中...";
            self.progressView.hidden = YES;
            break;
            
        case DecompressionFinish_State:
            self.stateBtn.hidden = YES;
            self.stateLab.hidden = NO;
            self.stateLab.text = @"已经是最新版本！";
            self.progressView.hidden = YES;
            break;
            
        default:
            break;
    }
}
@end
